package jsyf.oa.web.wechat.service_account.controller;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import jsyf.com.util.BaseUtils;
import jsyf.com.util.ResponseUtils;
import jsyf.oa.entity.wechat.service_account.WechatOAuthTokenEntity;
import jsyf.oa.entity.wechat.service_account.WechatOAuthUserEntity;
import jsyf.oa.facade.wechat.service_account.WechatOAuthFacade;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@SuppressWarnings("all")
@Api(value = "服务号-网页授权获取用户信息", description = "服务号-网页授权获取用户信息")
@Controller
@RequestMapping("/weChatOAuth")
public class WechatOAuthController {

    /**
     * 请求授权地址：
     * https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxff23c8d38b8afdf5&redirect_uri=http%3A%2F%2F127.0.0.1%3A8000%2Fpage%2FweChat%2FserviceAccount%2Ftemplate%2Flist.html&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
     */

    @Resource
    private WechatOAuthFacade wechatOAuthFacade;

    @RequestMapping(value = "/getUserInfo.json", method = RequestMethod.POST)

    public void getUserInfo(HttpServletResponse response, @RequestBody String jsonData) {

        JSONObject jsonObject = (JSONObject) JSONObject.parse(jsonData);
        // 用户同意授权后，能获取到code
        String code = jsonObject.getString("code");
        String state = jsonObject.getString("state");
        // 用户同意授权
        if (!"authdeny".equals(code)) {
            // 获取网页授权access_token
            JSONObject tokenEntity = wechatOAuthFacade.getOAuthTokenEntity(code);

            // 网页授权接口访问凭证
            String accessToken = tokenEntity.getString("access_token");
            // 用户标识
            String openId = tokenEntity.getString("openid");
            // 获取用户信息
            JSONObject userEntity = wechatOAuthFacade.getOAuthUserEntity(accessToken, openId);

            if (userEntity != null) {
                ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjTimeRespond(userEntity));
            } else {
                ResponseUtils.putJsonResponse(response, BaseUtils.errorrRespond("未找到数据"));
            }
        }
    }
}
